package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private UserServiceImpl userService;


    @Resource
    private StringRedisTemplate stringredisTemplate;

    @Override
    public Result queryBlogById(Long id) {
        //1.根据id查询博客(基本信息)
        Blog blog = this.getById(id);
        if (blog == null) {
            return Result.fail("该博客不存在");
        }
        //2.在查询blog表新增的用户信息
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        //3.查询blog是否被点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    public void isBlogLiked(Blog blog) {
        //1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前用户是否点赞
        String key = BLOG_LIKED_KEY + blog.getId();
        Boolean isLike = stringredisTemplate.opsForSet().isMember(key, userId.toString());
        blog.setIsLike(BooleanUtil.isTrue(isLike));
    }

    @Override
    public Result likeBlog(Long id) {

        //1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前用户是否点赞
        String key = BLOG_LIKED_KEY + id;
        Boolean isLike = stringredisTemplate.opsForSet().isMember(key, userId.toString());
        if (BooleanUtil.isFalse(isLike)) {
            //3如果未点赞，可以点赞
            //3.1数据库点赞+1
            boolean isSuccess = this.update().setSql("liked = liked + 1").eq("id", id).update();
            //3.2保存用户到redis的set集合中
            if (isSuccess) {
                stringredisTemplate.opsForSet().add(key, userId.toString());
            }
        } else {
            //4如果点赞，可取消点赞
            //4.1数据库点赞-1
            boolean isSuccess = this.update().setSql("liked = liked - 1").eq("id", id).update();
            //4.2移除用户到redis的set集合中
            if (isSuccess) {
                stringredisTemplate.opsForSet().remove(key, userId.toString());
            }
        }
        return Result.ok();

    }
}
